package com.pig4cloud.pig.ads.exception;

import com.pig4cloud.pig.common.core.exception.BaseException;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author helei
 */
@ControllerAdvice
@Slf4j
public class PigExceptionHandler {


	/**
	 * 基础异常
	 */
	@ExceptionHandler(BaseException.class)
	@ResponseBody
	public  R baseException(BaseException e) {
		return R.failed(e.getDefaultMessage());
	}

	/**
	 * 业务异常
	 */
	@ExceptionHandler(BusinessException.class)
	@ResponseBody
	public  R businessException(BusinessException e) {
		if (0 != e.getCode()) {
			return R.failed(e.getMessage());
		}
		return R.failed(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public  R handleException(Exception e) {
		log.error(e.getMessage(), e);
		if (e instanceof AccessDeniedException) {
			return R.failed("您无权访问,请重新登录后再进行操作");
		} else {
			return R.failed("操作异常");
		}

	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public  R validatedBindException(BindException e) {
		log.error(e.getMessage(), e);
		String message = e.getAllErrors().get(0).getDefaultMessage();
		return R.failed(message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public R validExceptionHandler(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return  R.failed(message);
	}
}
